package com.example.demo.controller;

import com.example.demo.constant.Constants;
import com.example.demo.model.Result;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", produces = "application/json")
    public Result login(String userName, String password, HttpSession session) {
        //1.校验参数
        //2.验证密码是否正确
        //3.返回响应结果
        log.info("用户登录, 账号:{}, 密码:{}", userName, password);
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码错误");
        }

        //根据用户的名称查询用户信息, 如果未查询到, 说明用户不存在
        ///如果查询到用户, 比对密码是否正确
        UserInfo userInfo = userService.getUserInfoByName(userName);
        if(userInfo == null) {
            return Result.fail("用户不存在");
        }
        //用户存在, 校验密码是否正确
        if(!password.equals(userInfo.getPassword())) {
            return Result.fail("密码错误");
        }

        //正确的情况
        session.setAttribute(Constants.USER_SESSION_KEY,userInfo);
        return Result.success("");
    }
}
